package name.wilbur.course.db.bigone.dao.impl;

import java.sql.SQLException;

import name.wilbur.course.db.bigone.dao.BaseDAO;
import name.wilbur.course.db.bigone.dao.DAOFactory;
import name.wilbur.course.db.bigone.model.Friend;
import name.wilbur.course.db.bigone.model.User;


/**
 * @author wilbur
 */
public class FriendDAO extends BaseDAO implements IFriendDAO {
	public FriendDAO() {
		super(Friend.class);
	}
	
	public User[] findFriends(int userID) {
		UserDAO UserDao = null;
		String whereClause = " WHERE UserID = '" + userID + "'";
		String sql = "SELECT UserID2 FROM " + table + whereClause;
		String sqlCnt = "SELECT COUNT(UserID2) FROM " + table + whereClause;
		int friends_num = 0;
		User[] users = null;
		try {
			queryNotClose(sqlCnt);
			if (rs.next())
				friends_num = rs.getInt(1);
			if (friends_num <= 0)
				return null;
			users = new User[friends_num];
			closeConnection();
			
			UserDao = (UserDAO) DAOFactory.createDAO(UserDAO.class);
			queryNotClose(sql);
			for (int i=0;rs.next();i++) {
				users[i] = (User)UserDao.findByPK(rs.getInt(1));
			}
			closeConnection();
		
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return users;
	}

	public boolean deleteFriend(int myID, int friendID) {
		try {
			log().debug("Deleting " + table + " by myID: " + myID + " friendID: " + friendID);
			conn = ds.getConnection();
			stmt = conn.createStatement();
			String sql = "DELETE FROM Friends WHERE UserID = '" + myID + "'" + 
					" AND UserID2 = '" + friendID + "'";
			log().debug(sql);
			stmt.executeUpdate(sql);
			return true;
		} catch (SQLException e) {
			e.printStackTrace();
			return false;
		} finally {
			closeConnection();
		}
	}
}
